package com.musollo;

import java.io.File;
import java.util.logging.LogManager;

import org.apache.log4j.Logger;
import org.slf4j.bridge.SLF4JBridgeHandler;

import com.musollo.domain.MP3Indexer;
import com.musollo.exceptions.GenPuidException;
import com.musollo.exceptions.IndexException;
import com.musollo.mp3tools.AbstractMP3Categorizer;
import com.musollo.mp3tools.categorizers.SimpleCategorizer;
import com.musollo.mp3tools.jaudiotagger.JAudioTaggerReader;
import com.musollo.mp3tools.jaudiotagger.JAudioTaggerWriter;
import com.musollo.mp3tools.jaudiotagger.MusicBrainzUpdater;

/**
 * The class that starts it all. The process can be broken down in three steps,
 * which are:
 * 
 * 1. Indexing the MP3's on the harddrive 2. Updating the MP3's on the harddrive
 * with updated songinformation 3. Categorising the MP3's on the harddisk
 * 
 * @author paw.janssen
 * 
 */
public final class MusolloApplication {
	private static MusolloApplication instance;
	private static final Logger LOG = Logger.getLogger(MusolloApplication.class);

	/**
	 * Retreive the instance of the MusolloApplication to work with it.
	 * 
	 * @return - The musollo application object.
	 */
	public static MusolloApplication getInstance() {
		if (MusolloApplication.instance == null) {
			MusolloApplication.instance = new MusolloApplication();
		}

		return MusolloApplication.instance;
	}

	public static void main(final String[] args) {
		if (args.length == 0 || !args[0].equals("imsure")) {
			LOG
					.fatal("Are you absolutely positively sure you want to start? This application will categorize/move all youre MP3's to the target location and overwrite the existing tag information!");
			LOG
					.fatal("If you are completely positively sure, start the program with 'imsure' (no quotes) as command line argument");
		}

		LogManager.getLogManager().reset();
		SLF4JBridgeHandler.install();

		MusolloApplication.getInstance().startApplication();
	}

	private MusolloApplication() {
	}

	/**
	 * When calling this method, the application is started and runs once.
	 */
	public void startApplication() {
		LOG.info("Starting Musollo");
		AbstractMP3Categorizer categorizer = new SimpleCategorizer();
		categorizer.setTargetDir(new File(Configuration.getInstance().getTargetLocation()));
		try {
			new MP3Indexer(new File(Configuration.getInstance().getIndexLocation()), new JAudioTaggerReader(),
					new JAudioTaggerWriter(), new MusicBrainzUpdater(), categorizer);
		} catch (IndexException e) {
			LOG.error("Indexing error", e);
		} catch (GenPuidException e) {
			LOG.error("GenPuid error", e);
		}
	}

}
